package cn.comon.app.scan.service.impl;

import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.comon.app.scan.component.SysConfigBean;
import cn.comon.app.scan.entity.AsReportinfo;
import cn.comon.app.scan.service.AppDownloadProcessService;
import cn.comon.app.scan.service.AsReportinfoService;

/**
 * 根据举报信息提供的APP的URL，下载对应的APP软件
 * @author xujf
 *
 */
@Service
public class AppDownloadScheduler {
    @Autowired
    private AsReportinfoService asReportinfoService;
    // 执行次数
    private static int executeCout = 0;
    
    private static Logger logger = Logger.getLogger(AppDownloadScheduler.class.getName());
    
    public void startAppDownload(){
        try {
            logger.info("【开始启动第[" + executeCout + "]次APP下载任务...】");
            ThreadPoolExecutor executor = ThreadPoolService.getTheadPool("downLoadAppThreadPool");
            
            logger.info("APP下载任务线程池中等待下载队列中的线程数：" + executor.getQueue().size());
            logger.info("APP下载任务线程池中的线程数：" + executor.getPoolSize());
            logger.info("APP下载任务线程池正在执行的线程数：" + executor.getActiveCount());
            
            if (executor.getQueue().size() < Integer.parseInt(SysConfigBean.getProperty("app.download.size"))) {
                int recordNum = Integer.parseInt(SysConfigBean.getProperty("app.download.size")) - executor.getQueue().size();
                
                //检索数据表【as_reportinfo】，取得需要下载的appURL
                // 如果第一次执行下载任务，先加载数据库中状态为正在下载的数据（这部分数据可能是由系统重启导致）
                List<AsReportinfo> appDataList = null;
                if (executeCout == 0) {
                	asReportinfoService.updateDownloadState2Undownload();
                }
                appDataList = asReportinfoService.getDownloadApp(recordNum);
                
                if (appDataList != null && appDataList.size() > 0) {
                	logger.info("第[" + executeCout + "]次APP下载任务新增" + appDataList.size() + "条APP到下载队列中等待下载");
                    //下载前先将待下载记录下载结果更新为正在下载（downloadResult=-1）
                    asReportinfoService.updateDownloadState2ing(recordNum);
                    for (AsReportinfo asReportinfo:appDataList) {
                    	AppDownloadProcessService appDownloadProcess = new AppDownloadProcessServiceImpl(asReportinfo);
                        executor.execute(appDownloadProcess);
                    }
                }
            } else {
                logger.info("【下载队列已满，忽略本次下载任务...】");
            }

            
            logger.info("【第[" + executeCout + "]次APP下载任务启动完成，正在下载中...】");
        } catch (Exception e) {
            logger.error("【第[" + executeCout + "]次APP下载任务启动发生异常】" + e.getMessage());
        } finally {
        	executeCout ++;
        }
    }
}